package logic

import (
	"context"
	"fmt"
	"pet/models/mysql"

	"pet/petrpc/internal/svc"
	"pet/petrpc/petrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PetAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPetAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PetAddLogic {
	return &PetAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PetAddLogic) PetAdd(in *petrpc.PetAddRequest) (*petrpc.PetAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := mysql.DB.Debug().Begin()

	class := mysql.Class{
		Name: in.ClassName,
	}
	err := begin.Create(&class).Error
	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("分类添加失败")
	}

	pet := mysql.Pet{
		Name:    in.Name,
		Image:   in.Image,
		Content: in.Content,
		ClassId: int(in.ClassId),
	}
	err = begin.Create(&pet).Error
	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("添加失败")
	}

	return &petrpc.PetAddResponse{
		PetId: int64(pet.ID),
	}, nil
}
